package com.vehicle.repair.controller;

import com.vehicle.repair.model.Feedback;
import com.vehicle.repair.service.FeedbackService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;

@RestController
@RequestMapping("/api/feedbacks")
public class FeedbackController {
    private final FeedbackService feedbackService;

    public FeedbackController(FeedbackService feedbackService) {
        this.feedbackService = feedbackService;
    }

    @PostMapping
    public ResponseEntity<Feedback> addFeedback(@RequestBody Feedback feedback,
                                              @RequestParam Integer orderId) {
        try {
            Feedback savedFeedback = feedbackService.addFeedback(feedback, orderId);
            return ResponseEntity.ok(savedFeedback);
        } catch (IllegalArgumentException | IllegalStateException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<Feedback> getFeedbackById(@PathVariable Integer id) {
        Optional<Feedback> feedback = feedbackService.getFeedbackById(id);
        return feedback.map(ResponseEntity::ok)
                     .orElseGet(() -> ResponseEntity.notFound().build());
    }

    @GetMapping("/order/{orderId}")
    public ResponseEntity<Feedback> getFeedbackByOrder(@PathVariable Integer orderId) {
        try {
            Optional<Feedback> feedback = feedbackService.getFeedbackByOrder(orderId);
            return feedback.map(ResponseEntity::ok)
                         .orElseGet(() -> ResponseEntity.notFound().build());
        } catch (IllegalArgumentException e) {
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/average-rating")
    public ResponseEntity<Double> getAverageRating() {
        double average = feedbackService.getAverageRating();
        return ResponseEntity.ok(average);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteFeedback(@PathVariable Integer id) {
        feedbackService.deleteFeedback(id);
        return ResponseEntity.noContent().build();
    }
}
